<template>
  <div>
    <el-row v-if="global.username != null">
      <template v-for="(item, index) in flowList">
        <el-button size="mini" type="primary" plain @click="startFlow(item)">{{item.value}}</el-button>
      </template>
    </el-row>
    <el-row v-else>
      请选择用户登录
    </el-row>

    <el-dialog title="选择流程并发起" :visible.sync="dialogFlowVisible">
      <el-form>
        <el-form-item label="流程">
          {{flow.value}}
        </el-form-item>
        <el-form-item label="主题">
          <el-input type="text" v-model="theme"></el-input>
        </el-form-item>
        <el-form-item label="初始信息">
          <vue-json-editor v-model="content" :show-btns="false" :modes="['form']" mode="form" lang="zh">
          </vue-json-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFlowVisible = false">取 消</el-button>
        <el-button v-if="themeUnwatch == null" @click="addWatch()">添加主题监听</el-button>
        <el-button v-else @click="delWatch()">清空主题监听</el-button>
        <el-button type="primary" @click="handleStartFlow()">发 起</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import vueJsonEditor from 'vue-json-editor'
  import access from '../api/access.js'
  import global from '../global.js'

  export default {
    data() {
      return {
        global: global,
        dialogFlowVisible: false,
        flowList: [],
        flow: {},
        theme: null,
        content: null,
        themeUnwatch: null
      }
    },
    components: {
      vueJsonEditor
    },
    mounted: function() {
      access.listFlow().then(res => {
        this.flowList = res.data || []
      })
    },
    methods: {
      startFlow(flow) {
        this.flow = flow
        this.content = {
          ...flow.data
        }
        this.theme = flow.value
        this.dialogFlowVisible = true;
        this.watch
      },
      handleStartFlow() {
        let params = {...this.content}
        params._theme = this.theme
        access.startFlow(this.flow.key, params).then(res => {
          this.dialogFlowVisible = false
          this.loadTableData()
        }, res => {
          this.$message.error(res.message || '启动失败')
        })
      },
      addWatch() {
        this.themeUnwatch = this.themeUnwatch || this.$watch('theme', (value, old) => {
          console.log('theme was change:' + old + ' => ' + value)
        })
      },
      delWatch() {
        if (this.themeUnwatch) {
          this.themeUnwatch()
          this.themeUnwatch = null
        }
      }
    }
  }
</script>

<style>
  .jsoneditor-vue .jsoneditor {
    min-height: 200px;
  }
</style>
